/**
 * 用户类 controller
 */
const ApiErrorNames = require('../config/ApiErrorNames.js');
const APIError = require('../middlewares/result.js').APIError;
const userService = require('../service/user.js');

/**
 * 查询所有用户
 */

let findAllUser = async (ctx) => {
  let result = await userService.findAllUser();
  ctx.body = result;
};

let getUser = async (ctx) => {
  const user = ctx.session.user;
  let result = await userService.findUserById(user.userId);
  if (!result) {
    throw new APIError(ApiErrorNames.USER_NOT_EXIST);
  }
  ctx.rest(result);
};

/**
 * 用户登录
 */
let login = async (ctx) => {
  let userData = ctx.request.body;
  const user = await userService.checkLogin(userData);
  ctx.session.user = user;
  const {userId, ...otherData} = user;
  ctx.rest(otherData);
};

/**
 * 注册用户
 */
let regist = async (ctx) => {
  let userData = ctx.request.body; // name password
  let result = await userService.addUser(userData);
  ctx.rest({
    userInfo: result,
  });
};


/**
 * 更新用户信息
 */

const updateInfo = async (ctx) => {
  const data = ctx.request.body;
  const user = ctx.session.user;
  let result = await userService.updateUserDataByUserId({...user, ...data});
  ctx.rest(result);
};


module.exports = {
  findAllUser,
  login,
  regist,
  getUser,
  updateInfo,
};
